package com.mcxx.modules.miniSalvation.family.service.read;

import com.google.common.collect.Lists;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.base.utils.excel.ImportExcel;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.check.param.CompareBizParam;
import com.mcxx.modules.miniSalvation.family.dao.read.BizCheckReadDao;
import com.mcxx.modules.miniSalvation.family.dao.write.BizCheckWriteDao;
import com.mcxx.modules.miniSalvation.family.entity.BizCompareEntity;
import com.mcxx.modules.miniSalvation.family.entity.IdCardAllBizEntity;
import com.mcxx.modules.miniSalvation.fundpay.entity.FundPayMemberEntity;
import com.mcxx.modules.system.entity.TaskExportEntity;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.AreaUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.core.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;


@Service
@TaTransactional
public class BizCheckService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(BizCheckService.class);

    @Autowired
    private BizCheckWriteDao bizCheckWriteDao;

    @Autowired
    private BizCheckReadDao bizCheckReadDao;

    @Autowired
    private AreaUtil areaUtil;

    @Autowired
    private TaskExportWriteService taskExportWriteService;

    @Autowired
    private ExportExcelService exportExcelService;

    @Autowired
    private FileService fileService;


    public List<FundPayMemberEntity> importCompareFile(MultipartFile file) {
        List<FundPayMemberEntity> excelPersonInfo = null;
        logger.info("开始解析上传的文件");
        excelPersonInfo = ImportExcel.importExcelPersonInfo(file);

        logger.info("解析文件完毕");
        return excelPersonInfo;
    }


    public BaseResult<List<IdCardAllBizEntity>> generateCompareData(MultipartFile file, UserAccountVo accountVo) {

        BaseResult<List<IdCardAllBizEntity>> resultMap = new BaseResult<>();

        List<FundPayMemberEntity> list = this.importCompareFile(file);

        Date monthFirst = DateUtils.getFirstDayOfMonth(new Date());
        String date = DateUtil.date2Str(monthFirst, DateUtil.sdf2);
        String curDate = DateUtil.date2Str(new Date(), DateUtil.sdf2);


        CompareBizParam params = new CompareBizParam();
        params.setCreateTime(curDate);
        String validCode = areaUtil.getValidCode(accountVo.getAreaCode());
        params.setAreaCode(validCode);
        List<IdCardAllBizEntity> resultsDB = bizCheckReadDao.queryCompareBizData(params);
        if (null != resultsDB && !resultsDB.isEmpty()) {
            List<String> ids = resultsDB.stream().map(IdCardAllBizEntity::getId).collect(Collectors.toList());
            bizCheckWriteDao.batchDeleteCompareData(ids);
        }


        List<String> idCards = list.stream().map(FundPayMemberEntity::getIdcard).collect(toList());


        List<BizCompareEntity> minPovertyList = bizCheckReadDao.getMinOrPovertyBiz(idCards, validCode);


        List<String> minIdCards = minPovertyList.stream().map(BizCompareEntity::getMemberIdCard).collect(Collectors.toList());


        List<BizCompareEntity> sameExist = new ArrayList<>(minPovertyList);
        if (!minIdCards.isEmpty()) {
            List<BizCompareEntity> tempList = bizCheckReadDao.getTempBiz(minIdCards, date, validCode);
            sameExist.addAll(tempList);


            List<BizCompareEntity> lowerList = bizCheckReadDao.getLowerBiz(minIdCards, validCode);
            sameExist.addAll(lowerList);
        }


        Map<String, List<BizCompareEntity>> cardMap = sameExist.stream().collect(Collectors.groupingBy(BizCompareEntity::getMemberIdCard));

        List<IdCardAllBizEntity> results = new ArrayList<>();

        generateBizData(list, cardMap, results, curDate);

        List<String> hasTempAndLower = new ArrayList<>();

        List<String> diffCards =
                idCards.stream().filter(item -> !new ArrayList<>(minIdCards).contains(item)).collect(Collectors.toList());
        if (!diffCards.isEmpty()) {
            List<BizCompareEntity> tempListSingle = bizCheckReadDao.getTempBiz(diffCards, date, validCode);

            List<String> hasTemp = tempListSingle.stream().map(BizCompareEntity::getMemberIdCard).collect(Collectors.toList());


            List<BizCompareEntity> lowerListSingle = bizCheckReadDao.getLowerBiz(diffCards, validCode);

            List<String> hasLower = lowerListSingle.stream().map(BizCompareEntity::getMemberIdCard).collect(Collectors.toList());


            List<BizCompareEntity> diffExist = new ArrayList<>();
            diffExist.addAll(tempListSingle);
            diffExist.addAll(lowerListSingle);


            Map<String, List<BizCompareEntity>> cardDiffExistMap = diffExist.stream().collect(Collectors.groupingBy(BizCompareEntity::getMemberIdCard));

            generateBizData(list, cardDiffExistMap, results, curDate);
            hasTempAndLower.addAll(hasTemp);
            hasTempAndLower.addAll(hasLower);
        }

        List<String> noBizIdCard = diffCards.stream().filter(item -> !new ArrayList<>(hasTempAndLower).contains(item)).collect(Collectors.toList());
        List<String> hasBizIdCard = idCards.stream().filter(item -> !new ArrayList<>(noBizIdCard).contains(item)).collect(Collectors.toList());


        List<List<IdCardAllBizEntity>> resultList = Lists.partition(results, 1024);
        for (List<IdCardAllBizEntity> subList : resultList) {
            bizCheckWriteDao.insertCompareBizData(subList);
        }
        resultMap.setData(results);
        resultMap.setMsg("此次操作共导入【" + idCards.size() + "】个比对身份证号，导入成功【" + hasBizIdCard.size() + "】条,导入失败【" + noBizIdCard.size() + "】条");
        return resultMap;
    }


    private void generateBizData(List<FundPayMemberEntity> list, Map<String, List<BizCompareEntity>> cardMap,
                                 List<IdCardAllBizEntity> results, String date) {
        Set<String> keySet = cardMap.keySet();
        Iterator<String> it = keySet.iterator();
        while (it.hasNext()) {
            String idCardKey = it.next();
            List<BizCompareEntity> personBiz = cardMap.get(idCardKey);

            Map<String, List<BizCompareEntity>> bizMap = personBiz.stream().collect(Collectors.groupingBy(BizCompareEntity::getBizType));
            Set<String> bizKeySet = bizMap.keySet();
            Iterator<String> bizIt = bizKeySet.iterator();

            IdCardAllBizEntity idCardBiz = new IdCardAllBizEntity();
            FundPayMemberEntity excelMember = list.stream().filter(item -> item.getIdcard().equals(idCardKey)).findFirst().get();
            idCardBiz.setExcelName(excelMember.getName());
            idCardBiz.setExcelIdCard(excelMember.getIdcard());
            idCardBiz.setCreateTime(date);
            idCardBiz.setId(Constant.getUUID());

            while (bizIt.hasNext()) {
                String bizKey = bizIt.next();
                List<BizCompareEntity> biz = bizMap.get(bizKey);
                BizCompareEntity sysMemberBiz = null;
                if (!biz.isEmpty()) {
                    sysMemberBiz = biz.get(0);
                    idCardBiz.setSysIdCard(sysMemberBiz.getMemberIdCard());
                    idCardBiz.setSysName(sysMemberBiz.getMemberName());
                    idCardBiz.setAreaCode(sysMemberBiz.getAreaCode());
                    idCardBiz.setStreet(sysMemberBiz.getStreet());
                    idCardBiz.setCommunity(sysMemberBiz.getCommunity());
                    idCardBiz.setSex(sysMemberBiz.getSex());
                    if (Constant.BusinessCode.DIBAO.equals(bizKey)) {
                        idCardBiz.setMinStandType(sysMemberBiz.getStandType());
                        idCardBiz.setMinSalary(sysMemberBiz.getSalary());
                    }
                    if (Constant.BusinessCode.TEKUN.equals(bizKey)) {
                        idCardBiz.setExStandType(sysMemberBiz.getStandType());
                        idCardBiz.setExSalary(sysMemberBiz.getSalary());
                    }
                    if (Constant.BusinessCode.LINSHI.equals(bizKey)) {
                        idCardBiz.setTempSalary(sysMemberBiz.getSalary());
                    }
                    if (Constant.BusinessCode.DISHOURU.equals(bizKey)) {
                        idCardBiz.setLowerState(sysMemberBiz.getStatus());
                    }
                }
            }
            results.add(idCardBiz);
        }
    }


    public Page queryCompareBizData(CompareBizParam compareBizParam, PageParam pageParam, UserAccountVo curUserAccount) {
        String curDate = DateUtil.date2Str(new Date(), DateUtil.sdf2);
        compareBizParam.setCreateTime(curDate);

        QueryParamUtil.setBaseParamValue(compareBizParam, curUserAccount);

        bizCheckReadDao.beginPager(pageParam);
        List<IdCardAllBizEntity> results = bizCheckReadDao.queryCompareBizData(compareBizParam);

        return bizCheckReadDao.endPager(results);
    }


    public ExcelInfo exportCompareData(CompareBizParam param, UserAccountVo accountVo) {
        String curDate = DateUtil.date2Str(new Date(), DateUtil.sdf2);
        param.setCreateTime(curDate);
        param.setAreaCode(areaUtil.getValidCode(accountVo.getAreaCode()));
        Workbook workbook = null;
        ExcelInfo excelInfo = null;
        List<IdCardAllBizEntity> results = bizCheckReadDao.queryCompareBizData(param);


        workbook = exportExcelService.exportWorkBook(IdCardAllBizEntity.class, results,
                "数据核对信息", "数据核对列表", false);

        if (null != workbook) {
            Sheet sheet = workbook.getSheetAt(0);
            sheet.shiftRows(1, sheet.getLastRowNum(), 1);
            Row rowOne = sheet.createRow(1);
            rowOne.setHeight((short) 500);
            for (int i = 0; i < 14; i++) {
                rowOne.createCell(i);
            }

            Cell cellOne = rowOne.getCell(0);
            cellOne.setCellValue("比对对象姓名");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(1);
            cellOne.setCellValue("比对对象身份证");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(2);
            cellOne.setCellValue("区县");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(3);
            cellOne.setCellValue("街道（乡镇）");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(4);
            cellOne.setCellValue("系统姓名");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(5);
            cellOne.setCellValue("系统身份证");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(6);
            cellOne.setCellValue("性别");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(7);
            cellOne.setCellValue("最低生活保障");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(9);
            cellOne.setCellValue("特困救助人员供养");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(11);
            cellOne.setCellValue("临时救助");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(12);
            cellOne.setCellValue("低边缘家庭");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            cellOne = rowOne.getCell(13);
            cellOne.setCellValue("对比时间");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);



            CellRangeAddress region = new CellRangeAddress(1, 1, 7, 8);
            sheet.addMergedRegion(region);
            CellRangeAddress region1 = new CellRangeAddress(1, 1, 9, 10);
            sheet.addMergedRegion(region1);



            CellRangeAddress region10 = new CellRangeAddress(1, 2, 0, 0);
            sheet.addMergedRegion(region10);
            CellRangeAddress region11 = new CellRangeAddress(1, 2, 1, 1);
            sheet.addMergedRegion(region11);
            CellRangeAddress region12 = new CellRangeAddress(1, 2, 2, 2);
            sheet.addMergedRegion(region12);
            CellRangeAddress region13 = new CellRangeAddress(1, 2, 3, 3);
            sheet.addMergedRegion(region13);
            CellRangeAddress region14 = new CellRangeAddress(1, 2, 4, 4);
            sheet.addMergedRegion(region14);
            CellRangeAddress region15 = new CellRangeAddress(1, 2, 5, 5);
            sheet.addMergedRegion(region15);
            CellRangeAddress region16 = new CellRangeAddress(1, 2, 6, 6);
            sheet.addMergedRegion(region16);
            CellRangeAddress region17 = new CellRangeAddress(1, 2, 13, 13);
            sheet.addMergedRegion(region17);
            CellRangeAddress region18 = new CellRangeAddress(1, 2, 14, 14);
            sheet.addMergedRegion(region18);

            excelInfo = exportExcelService.exportExcelByWorkBook(workbook, results, "数据核对统计信息.xls");
        }


//            String objectkey = fileService.upload(sbs, excelInfo.getFileName());


//                taskExport.setId(Constant.getUUID());
//                taskExport.setUserid(accountVo.getUserId());
//                taskExport.setTaskName(excelInfo.getFileName());











        return excelInfo;
    }
}
